<template>
  <view class="personal-container">
    <scroll-view scroll-y class="scroll-view">
      <view class="content-area">
        <!-- 头像区域 -->
        <view class="avatar-section">
          <view class="avatar-container">
            <uv-avatar :size="120" :src="formData.avatar" shape="circle"></uv-avatar>
            <view class="avatar-edit-btn" @click="editAvatar">
              <uv-icon name="camera" size="20" color="#333"></uv-icon>
            </view>
          </view>
        </view>

        <!-- 表单区域 -->
        <view class="form-section">
          <view class="form-item">
            <view class="form-label">昵称</view>
            <view class="form-input">
              <uv-input
                v-model="formData.username"
                placeholder="请输入昵称"
                :border="false"
                :clearable="true"
                input-align="right"
              ></uv-input>
            </view>
          </view>

          <view class="form-item" @click="showGenderPicker">
            <view class="form-label">性别</view>
            <view class="form-value">
              <text class="value-text">{{
                formData.gender == '1' ? '男' : formData.gender == '0' ? '女' : '请选择性别'
              }}</text>
              <uv-icon name="arrow-right" size="16" color="#999"></uv-icon>
            </view>
          </view>

          <view class="form-item" @click="showDatePicker">
            <view class="form-label">生日</view>
            <view class="form-value">
              <text class="value-text">{{ formData.birthday || '请选择日期' }}</text>
              <uv-icon name="arrow-right" size="16" color="#999"></uv-icon>
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">身份证</view>
            <view class="form-input">
              <uv-input
                v-model="formData.idcard"
                placeholder="请输入身份证号"
                :border="false"
                :clearable="true"
                input-align="right"
                maxlength="18"
              ></uv-input>
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">居住地</view>
            <view class="form-input">
              <uv-input
                v-model="formData.address"
                placeholder="请填写居住地"
                :border="false"
                :clearable="true"
                input-align="right"
              ></uv-input>
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">公司名称</view>
            <view class="form-input">
              <uv-input
                v-model="formData.corporatename"
                placeholder="请输入公司名称"
                :border="false"
                :clearable="true"
                input-align="right"
              ></uv-input>
            </view>
          </view>
        </view>

        <!-- 保存按钮 -->
        <view class="save-button-section">
          <uv-button
            type="primary"
            text="保存"
            size="large"
            :custom-style="saveButtonStyle"
            @click="saveProfile"
          ></uv-button>
        </view>
      </view>
    </scroll-view>

    <!-- 性别选择器 -->
    <uv-picker
      ref="genderPickerRef"
      :columns="genderColumns"
      @confirm="onGenderConfirm"
    ></uv-picker>

    <!-- 日期选择器 -->
    <uv-datetime-picker
      ref="datePickerRef"
      mode="date"
      :value="currentDate"
      :minDate="minDate"
      :maxDate="maxDate"
      @confirm="onDateConfirm"
    ></uv-datetime-picker>
  </view>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { useRequest } from '@/api'
  const { API_MEMBER_INFO, API_MEMBER_SAVE } = useRequest()
  import { UserInfoManager } from '@/utils/userInfo'
  import { useAppStore } from '@/store/app'
  // 获取 store
  const appStore = useAppStore()
  
  // 表单数据
  const formData = reactive({
    avatar: '',
    username: '',
    gender: '',
    birthday: '',
    idcard: '',
    address: '',
    corporatename: ''
  })

  // 初始化表单数据
  const initFormData = async () => {
    const params = {
      isdriver: UserInfoManager.lastrole()
    }
    const res = await API_MEMBER_INFO(params)
    if (res.code === 1) {
      // 使用 Object.assign 来保持响应性
      Object.assign(formData, {
        avatar: res.data.avatar || '',
        username: res.data.username || '',
        gender: res.data.gender || '',
        birthday: res.data.birthday || '',
        idcard: res.data.idcard || '',
        address: res.data.address || '',
        corporatename: res.data.corporatename || ''
      })
    }
  }

  // 性别选择器
  const genderPickerRef = ref()
  const genderColumns = [['男', '女']]

  // 日期选择器
  const datePickerRef = ref()
  const currentDate = ref(Date.now())
  
  // 计算日期范围：开始时间往前推60年，结束时间到当前日期
  const now = new Date()
  const minDate = new Date(now.getFullYear() - 60, now.getMonth(), now.getDate())
  const maxDate = new Date()

  // 保存按钮样式
  const saveButtonStyle = {
    backgroundColor: '#FF6B35',
    borderColor: '#FF6B35',
    borderRadius: '24rpx',
    height: '88rpx',
    fontSize: '32rpx',
    fontWeight: '600'
  }
  // 编辑头像
  const editAvatar = () => {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log('选择图片成功:', res.tempFilePaths[0])
        // 上传头像到服务器
        uploadAvatar(res.tempFilePaths[0])
      },
      fail: (err) => {
        console.log('选择图片失败:', err)
        
      }
    })
  }

  // 上传头像
  const uploadAvatar = async (filePath: string) => {
    uni.showLoading({ title: '上传中...' })

    try {
      const uploadRes = await uni.uploadFile({
        url: import.meta.env.VITE_APP_API_BASEURL + '/api/index/upload',
        filePath: filePath,
        name: 'file',
        formData: {
          type: 'avatar' // 文件类型标识
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data)
            console.log('头像上传响应:', data)
            if (data.code === 1) {
              // 上传成功，更新头像
              formData.avatar = data.data.fullurl
              uni.showToast({ title: '头像更新成功', icon: 'success' })
            } else {
              uni.showToast({ title: data.msg || '上传失败', icon: 'none' })
            }
          } catch (e) {
            console.error('解析上传响应失败:', e)
            uni.showToast({ title: '上传失败', icon: 'none' })
          }
        },
        fail: (err) => {
          console.error('头像上传失败:', err)
          uni.showToast({ title: '上传失败', icon: 'none' })
        }
      })
    } catch (error) {
      console.error('头像上传异常:', error)
      uni.showToast({ title: '上传异常', icon: 'none' })
    } finally {
      uni.hideLoading()
    }
  }

  // 显示性别选择器
  const showGenderPicker = () => {
    genderPickerRef.value?.open()
  }

  // 性别选择确认
  const onGenderConfirm = (e: any) => {
    formData.gender = e.value[0] === '男' ? '1' : '0'
  }

  // 显示日期选择器
  const showDatePicker = () => {
    datePickerRef.value?.open()
  }

  // 日期选择确认
  const onDateConfirm = (e: any) => {
    const date = new Date(e.value)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    formData.birthday = `${year}-${month}-${day}`
  }

  // 保存个人资料
  const saveProfile = async () => {
    // 验证必填字段
    if (!formData.username.trim()) {
      uni.showToast({ title: '请输入昵称', icon: 'none' })
      return
    }

    // 验证身份证号
    if (formData.idcard && !/^\d{17}[\dXx]$/.test(formData.idcard)) {
      uni.showToast({ title: '请输入正确的身份证号', icon: 'none' })
      return
    }
    uni.showLoading({ title: '保存中...' })
    try {
      const isDriver = UserInfoManager.lastrole()
      const params = {
        isdriver: isDriver,
        username: formData.username,
        gender: formData.gender,
        birthday: formData.birthday,
        idcard: formData.idcard,
        address: formData.address,
        corporatename: formData.corporatename,
        avatar: formData.avatar
      }

             const res = await API_MEMBER_SAVE(params)
       if (res.code === 1) {
         // 保存成功后，更新本地用户信息
         const currentUserInfo = UserInfoManager.getUserInfo()
         if (currentUserInfo) {
           // 更新用户信息，保留原有字段，更新修改的字段
           const updatedUserInfo = {
             ...currentUserInfo,
             username: formData.username,
             gender: formData.gender,
             birthday: formData.birthday,
             idcard: formData.idcard,
             address: formData.address,
             corporatename: formData.corporatename,
             avatar: formData.avatar
           }
           
           // 保存更新后的用户信息
           UserInfoManager.setUserInfo(updatedUserInfo)
           
           // 同时更新 Pinia store 中的用户信息
           appStore.setUserInfo(updatedUserInfo)
           
           console.log('用户信息已更新:', updatedUserInfo)
         }
         
         uni.showToast({ title: '保存成功', icon: 'success' })

         // 延迟返回上一页
         setTimeout(() => {
           uni.navigateBack()
         }, 500)
       } 
    } catch (error) {
      
    } finally {
      uni.hideLoading()
    }
  }

  // 页面加载时初始化数据
  onMounted(() => {
    initFormData()
  })
</script>

<style lang="scss" scoped>
  // 头像区域
  .avatar-section {
    display: flex;
    justify-content: center;
    margin: 48rpx 0;

    .avatar-container {
      position: relative;
      display: inline-block;

      .avatar-edit-btn {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 40rpx;
        height: 40rpx;
        background: #fff;
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
        border: 2rpx solid #f0f0f0;
      }
    }
  }

  // 表单区域
  .form-section {
    width: 100%;
    .form-item {
      display: flex;
      align-items: center;
      min-height: 96rpx;
      padding: 32rpx;
      border-bottom: 1rpx solid #f0f0f0;
      transition: background-color 0.2s ease;

      &:last-child {
        border-bottom: none;
      }

      &:active {
        background-color: #f8f9fa;
      }

      .form-label {
        width: 160rpx;
        flex: 0 0 160rpx;
        font-size: 32rpx;
        color: #333;
        font-weight: 500;
      }

      .form-input {
        flex: 1;
        margin-left: 24rpx;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }

      .form-value {
        flex: 1;
        margin-left: 24rpx;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .value-text {
          font-size: 30rpx;
          color: #333;
          text-align: right;
          &:empty::before {
            content: attr(placeholder);
            color: #999;
          }
        }
      }
    }
  }

  // 保存按钮区域
  .save-button-section {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 32rpx;
    background: #fff;
    box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
  }

  // 深度样式调整
  :deep(.uv-input__input) {
    font-size: 32rpx !important;
    color: #333 !important;
    text-align: right !important;
  }

  :deep(.uv-input__placeholder) {
    color: #999 !important;
    font-size: 32rpx !important;
    text-align: right !important;
  }
</style>
